﻿using System;
using System.Web;
using MayhemServer.Extensions;
using MayhemServer.Services;

namespace MayhemServer.Handlers {
    public class PackageDownloadHandler : IHttpHandler {
        private const string urlPrefix = "/nupkg-redir/";
        private readonly IPackageDetailService packageDownloadService;

        public PackageDownloadHandler() {
            packageDownloadService = new PackageDetailService();
        }

        public bool IsReusable {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context) {
            var url = context.Request.RawUrl;
            if (url.StartsWith(urlPrefix, StringComparison.InvariantCultureIgnoreCase)) {
                var packageDownloadId = short.Parse(context.Request.RawUrl.Remove(0, urlPrefix.Length));
                var package = packageDownloadService.Increment(packageDownloadId);
                context.Response.Redirect(package.GetDownloadUrl());
            }
        }
    }
}